import {observable, action} from 'mobx';
import {Auth} from '../models';
import UserInfoStore from './userInfo';
import HistoryStore from './history';
import ImageStore from './image';

class AuthStore {
    @observable values = {
        username: '',
        password: ''
    };

    @action setUsername(username: string) {
        this.values.username = username;
    }

    @action setPassword(password: string) {
        this.values.password = password;
    }

    @action login() {
        return new Promise((resolve, reject) => {
            Auth.login(this.values.username, this.values.password)
                .then(user => {
                    console.log(`${user}登录成功`);
                    UserInfoStore.pullUser();
                    resolve(user);
                })
                .catch(error => {
                    console.log(error);
                    UserInfoStore.resetUser();
                    reject(error);
                });
        });
    }

    @action register() {
        return new Promise((resolve, reject) => {
            Auth.register(this.values.username, this.values.password)
                .then(user => {
                    console.log(`${user}注册成功`);
                    UserInfoStore.pullUser();
                    resolve(user);
                })
                .catch(error => {
                    console.log(error);
                    UserInfoStore.resetUser();
                    reject(error);
                });
        });
    }

    @action logout() {
        Auth.logout();
        UserInfoStore.resetUser();
        HistoryStore.reset();
        ImageStore.reset();
    }
}

export default new AuthStore();